package org.study.locks.tools;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierExample implements Runnable {

    private CyclicBarrier barrier;
    private String name;


    @Override
    public void run() {
        try {
            Thread.sleep(1000 * (new Random()).nextInt(5));
            System.out.println(name + " 准备OK.");
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(name + " Go!!");
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(3);  // 3 
        ExecutorService executor = Executors.newFixedThreadPool(3);

        executor.submit(new CyclicBarrierExample());
        executor.submit(new CyclicBarrierExample());
        executor.submit(new CyclicBarrierExample());

        executor.shutdown();
    }

}  